<template>
  <div>
    <div class="login-title">
      <p class="title">欢迎登录 · 售后服务管理商家端</p>
    </div>
    <div class="tabs">
      <div class="tab_display">
        <div class="tab" :class="{ tab_temp: tab_temp_index == 2 }" @click="tab_temp(2)">账号登录</div>
        <div class="tab" :class="{ tab_temp: tab_temp_index == 1 }" @click="tab_temp(1)">短信登录</div>
      </div>
    </div>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="0">
      <el-form-item prop="phone" class="el-item_login">
        <el-input placeholder="请输入手机号" maxlength="11" type="tel" clearable autoComplete="off" v-model="ruleForm.phone">
        </el-input>
      </el-form-item>
      <el-form-item prop="password" v-if="tab_temp_index == 2">
        <el-input placeholder="请输入登录密码" clearable v-model="ruleForm.password"
          @keyup.enter.native="submitForm(ruleFormRef)" :type="passwordType" @input="ruleForm.password=ruleForm.password.replace(/[\u4E00-\u9FA5\s]/g,'')">
          <template #suffix>
            <div @click="showPwd"><svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" /></div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item v-else prop="code">
        <el-input placeholder="请输入验证码" autoComplete="on" maxlength="6"  @input="ruleForm.code=ruleForm.code.replace(/[\u4E00-\u9FA5\s]/g,'')" v-model="ruleForm.code"
          @keyup.enter.native="submitForm(ruleFormRef)">
          <template #suffix>
            <div class="getcode" @click="getCode" v-if="count == 0">获取验证码</div>
            <div class="getcode" v-else>{{ count }}s重新获取</div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <div class="check">
          <div class="check_left">
            <el-checkbox v-model="checked1" size="large">
              <span>记住账号</span>
            </el-checkbox>
          </div>
          <div class="check_right" @click="forGet">忘记密码</div>
        </div>
      </el-form-item>
      <el-form-item>
        <div class="agree">
          登录即代表已阅读并同意&nbsp;<a href="/agreement/index.html" rel="noopener" target="_blank">用户协议</a>
        </div>
      </el-form-item>
      <el-form-item style="width: 100%" v-if="tab_temp_index == 2">
        <el-button :loading="loading" class="login-btn" :disabled="!(ruleForm.phone && ruleForm.password)" type="primary"
          color="#007cff" @click="submitForm(ruleFormRef)">登录</el-button>
      </el-form-item>
      <el-form-item style="width: 100%" v-else>
        <el-button :loading="loading" class="login-btn" :disabled="!(ruleForm.phone && ruleForm.code)" type="primary"
          color="#007cff" @click="submitForm(ruleFormRef)">登录</el-button>
      </el-form-item>
    </el-form>
    <div class="text">没有账号？
      <div class="goRegister" @click="goRegister">我要注册</div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, watch, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '../../../store/modules/user'
import { loginCode, getCustomer, login } from '../../../api/user'
import { phone, passwordLength, password } from '../../../utils/validate'
import md5 from 'js-md5'  //引入md5 加密
import * as  _ from 'lodash'
import { initWebSocket } from '../../../utils/socket';

import { ElMessageBox } from 'element-plus'


const ruleFormRef = ref<FormInstance>()
const router = useRouter()
const UserStore = useUserStore()
const tab_temp_index = ref(2)
const clear = ref(null)
const passwordType = ref('password')
const loading = ref(false)
// 表单数据
const ruleForm = reactive({
  phone: '',
  password: '',
  code: '',
})
const rules = reactive({
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: phone(ruleForm.phone), trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: passwordLength(ruleForm.password), trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入正确的验证码', trigger: 'blur' },
    { pattern: /^\d*$/, message: '请输入正确的验证码', trigger: 'blur' },
  ],
})
const checked1 = ref(JSON.parse(localStorage.getItem('checked1'))?.value || false)
// 倒计时
const count = ref(0)
const showPwd = () => {
  if (passwordType.value === 'password') {
    passwordType.value = ''
  } else {
    passwordType.value = 'password'
  }
}
function funGetmrg(msg) {
  if (msg.code == 40102) {
    UserStore.token = null
    UserStore.roles = []
    UserStore.row = {
      tokenValue: null,//登录token
      expireIn: null,//过期时间   
      tokenStartTime: null,//登录当前时间
      refreshToken: null,//刷新token
      tokenName: null,
    }
    ElMessageBox.confirm(msg.message, '温馨提示', {
      confirmButtonText: '确定',
      type: 'error',
      showCancelButton: false,
      showClose: false,
      closeOnClickModal: false,
      closeOnPressEscape: false,
    })
      .then(async () => {
        UserStore.logout()
        router.push({ path: '/login/index' })
      })
  }

}
// 注册页面
const goRegister = () => {
  router.push({ path: '/login/register' })
}
// 忘记密码
const forGet = () => {
  router.push({ path: '/login/forget' })
}
//md5密码加密
const { proxy } = getCurrentInstance() as any
proxy.$md5 = md5   //md5转换为vue原型

// 登录
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      loading.value = true
      // 登录
      let data = {
        password: '',
        phone: ruleForm.phone,
        rememberMe: checked1.value,
        loginType: tab_temp_index.value,
      }
      if (tab_temp_index.value == 2) {
        data.password = proxy.$md5(ruleForm.password)
      } else {
        data.password = ruleForm.code
      }

      login(data).then((res: any) => {
        loading.value = false
        if (res?.data?.code == 20000) {
          UserStore.row = { ...res.data.data.row, tokenStartTime: new Date().getTime() }
          initWebSocket(funGetmrg, `/ws/login/${useUserStore().row.tokenValue}`)
          // 角色
          router.push({ path: '/login/roles' })
        } else {
          ElMessage({
            showClose: true,
            message: res?.data?.message || '登陆失败！',
            type: 'error',
            duration: 3000,
          })
        }
      })
    } else {
      ElMessage({
        showClose: true,
        message: '登陆失败！',
        type: 'error',
        duration: 3000,
      })
      return false
    }
  })
}
// 账号登录1  短信登录2
const tab_temp = (val: number) => {
  tab_temp_index.value = val
}
// 获取验证码
const getCode = () => {
  if (!ruleForm.phone) {
    ElMessage({
      showClose: true,
      message: '请先输入手机号',
      type: 'error',
      duration: 3000,
    })
    return
  }
  count.value = 59
  clear.value = setInterval(() => {
    count.value -= 1
    if (count.value == 0) {
      clearInterval(clear.value)
    }
  }, 1000)
  loginCode({ phone: ruleForm.phone }).then((res) => {
    if (res.data.success) {
      ElMessage({
        showClose: true,
        message: res.data.message,
        type: 'success',
        duration: 3000,
      })
    } else {
      ElMessage({
        showClose: true,
        message: res.data.message,
        type: 'error',
        duration: 3000,
      })
    }
  })
}

watch(
  () => checked1.value,
  (n) => {
    if (n) {
      // 设置过期时间七天
      let expiration = new Date().getTime() + 168 * 60 * 60 * 1000
      localStorage.setItem('phone', JSON.stringify({ value: ruleForm.phone, time: expiration }))
      localStorage.setItem(
        'checked1',
        JSON.stringify({ value: checked1.value, time: expiration }),
      )
      localStorage.setItem(
        'loginType',
        JSON.stringify({ value: tab_temp_index.value, time: expiration }),
      )
    } else {
      localStorage.removeItem('phone')
      localStorage.removeItem('checked1')
      localStorage.removeItem('loginType')
    }
  },
)
onMounted(() => {
  var storedData = JSON.parse(localStorage.getItem('phone'))
  if (storedData) {
    var currentTime = new Date().getTime()
    if (currentTime > storedData.time) {
      localStorage.removeItem('phone')
      localStorage.removeItem('checked1')
      localStorage.removeItem('loginType')
      storedData = null
    } else {
      ruleForm.phone = JSON.parse(localStorage.getItem('phone')).value
    }
  }
})
</script>

<style lang="scss" scoped>
@import '../index.scss';
</style>
<style  lang="scss">
input:-internal-autofill-previewed,
input:-internal-autofill-selected {
  // -webkit-text-fill-color: #FFFFFF !important;

  transition: background-color 5000s ease-in-out 10s !important;
}
</style>
